from django.contrib import admin

from create.models import Category, Story


# Register your models here.
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ['id', 'name']


@admin.register(Story)
class StoryAdmin(admin.ModelAdmin):
    list_display = [
        'id', 'title', 'category', 'date', 'creator',
        'get_like_count', 'get_collect_count'  # 引用自定义方法名
    ]

    list_display_links = ['id', 'title']
    search_fields = ['title', 'creator__username']
    list_filter = ['category', 'date']

    # ---------------------- 自定义统计方法 ----------------------
    def get_like_count(self, obj):
        """计算当前故事的点赞数（obj 是当前 Story 实例）"""
        return obj.likes.count()  # 多对多字段通过.count()统计数量

    def get_collect_count(self, obj):
        """计算当前故事的收藏数"""
        return obj.collects.count()